package com.foosun.core.controller;

import com.foosun.core.base.PageData;
import com.foosun.core.bean.FileBean;
import com.foosun.core.entity.FileObject;
import com.foosun.core.service.FileObjectService;
import com.foosun.core.util.PropertiesConfig;
import com.foosun.core.util.QrUtil;
import com.foosun.core.util.ServerUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: xi
 * Date: 14-1-2
 * Time: 上午10:49
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/common/file")
public class FileController {

    @Resource
    private FileObjectService fileObjectService;

    @Autowired
    private PropertiesConfig propertiesConfig;

    private String baseDownloadPath;

    private String getBaseDownloadPath(HttpServletRequest request) {
        if (baseDownloadPath == null) {
            baseDownloadPath = ServerUtil.getServerPath(request) + "/common/file/download/";
        }
        return baseDownloadPath;
    }

    @RequestMapping("/list")
    public String list(Model model, PageData<FileObject> pageData, HttpServletRequest request) throws Exception {
        pageData.setWebMap(request.getParameterMap());
        pageData = fileObjectService.findList(pageData);
        model.addAttribute("pageData", pageData);
        return "/common/file/list";
    }

    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id") Integer id) throws Exception {
        fileObjectService.delete(id);
        return "redirect:/common/file/list";// 重定向
    }

    @RequestMapping(value = "/list/files")
    @ResponseBody
    public List<FileObject> listFiles(String ids) throws Exception {
        List<FileObject> list = fileObjectService.findListByIds(ids);
        return list;
    }

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String upload(Model model) {
        return "/common/file/upload";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(@ModelAttribute("uploadForm") FileBean fileBean, HttpSession session, Model model) throws Exception {
        String uploadPath = propertiesConfig.getFileUplaodPath();
        List<MultipartFile> files = fileBean.getFiles();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            if (null != files && files.size() > 0) {
                for (MultipartFile multipartFile : files) {

//                    String originalName = new String(multipartFile.getOriginalFilename().getBytes("ISO8859-1"), "UTF-8");
                    String originalName = multipartFile.getOriginalFilename();
//                    String name = "T" + System.currentTimeMillis();
                    String name = UUID.randomUUID().toString();

                    inputStream = multipartFile.getInputStream();
                    File dir = new File(uploadPath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File newFile = new File(uploadPath + name);

                    if (!newFile.exists()) {
                        newFile.createNewFile();
                    }
                    outputStream = new FileOutputStream(newFile);
                    int read = 0;
                    byte[] bytes = new byte[1024];

                    int i = 0;
                    float total = inputStream.available();
                    while ((read = inputStream.read(bytes)) != -1) {
                        float percent = 10 + 100 * ((read + 1024 * i) / total);
                        outputStream.write(bytes, 0, read);
                        i++;
                    }
                    FileObject fileObject = new FileObject();
                    fileObject.setOriginal(originalName);
                    fileObject.setPath(uploadPath);
                    fileObject.setName(name);
                    fileObject.setUrl(propertiesConfig.getFileDownloadURL());
                    fileObject.setSuffix(originalName.substring(originalName
                            .lastIndexOf(".") + 1));
                    fileObject.setSize(multipartFile.getSize());
                    fileObjectService.save(fileObject);
                    fileObject = fileObjectService.findByPropertyOne("name", fileObject.getName());
                    model.addAttribute("fileObject", fileObject);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }

        return "/common/file/upload";
    }

    //    @RequestMapping("/download/{id}")
//    public ResponseEntity<byte[]> download(@PathVariable("id") Integer id) throws Exception {
//        FileObject fileObject = fileObjectService.findById(id);
//        if (fileObject != null) {
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//            headers.setContentDispositionFormData("attachment", new String(fileObject.getOriginal().getBytes("utf-8"), "ISO-8859-1"));
//            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(fileObject.getPath() + fileObject.getName())),
//                    headers, HttpStatus.CREATED);
//        }
//        return null;
//    }//
//
    @RequestMapping("/qr")
    public ResponseEntity<byte[]> download(String content, Integer h, Integer w) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        if (StringUtils.isNotBlank(content)) {
            h = (h == null || h == 0) ? 100 : h;
            w = (w == null || w == 0) ? 100 : w;
            QrUtil.genQRCode(out, content, w, h);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", new String((UUID.randomUUID().toString() + ".png").getBytes("utf-8"), "ISO-8859-1"));
            return new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.CREATED);
        } else {
            return null;
        }
    }

    @RequestMapping("/qr/{id}")
    public void download(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String content = getBaseDownloadPath(request) + id;
        int h = 350, w = 350;
        QrUtil.genQRCode(out, content, w, h);
        String realPath = request.getSession().getServletContext().getRealPath("/download");
        String fileName = "qr." + id + ".png";
        File qr = new File(realPath + "/" + fileName);
        if (!qr.exists()) {
            FileUtils.writeByteArrayToFile(qr, out.toByteArray());
        }
        response.sendRedirect(request.getContextPath() + "/download/" + fileName);

    }

    @RequestMapping("/download/{id}")
    public void download(@PathVariable("id") Integer id, HttpServletResponse response, HttpServletRequest request) throws Exception {
        FileObject fileObject = fileObjectService.findById(id);
        if (fileObject != null) {
            String realPath = request.getSession().getServletContext().getRealPath("/download");
            String fileName = fileObject.getName().replace("-", "").substring(20) + "." + fileObject.getId() + "." + fileObject.getSuffix();
            File download = new File(realPath + "/" + fileName);
            if (!download.exists()) {
                File copyFile = new File(fileObject.getPath() + fileObject.getName());
                if (copyFile.exists()) {
                    FileUtils.copyFile(copyFile, download);
                } else {
                    if (fileObject.getSuffix().toLowerCase().matches(".*(png|gif|jpg|jpeg)$")) {
                        response.sendRedirect(request.getContextPath() + "/static/new/style/images/no-img.png");
                        return;
                    } else {
                        throw new Exception("未找到资源...");
                    }
                }
            }
            response.sendRedirect(request.getContextPath() + "/download/" + fileName);
        }
    }

    @RequestMapping("/delete/all")
    public String deleteAll(Model model) throws Exception {
        fileObjectService.deleteAll();
        FileUtils.cleanDirectory(new File(propertiesConfig.getFileUplaodPath()));
        return "redirect:/common/file/list";// 重定向
    }

    @RequestMapping("/demo")
    public String demo(Model model) throws Exception {
        return "/common/file/demo";// 重定向
    }

    @RequestMapping("/info/{id}")
    @ResponseBody
    public FileObject deleteAll(@PathVariable("id") Integer id) throws Exception {
        FileObject fileObject = fileObjectService.findById(id);
        return fileObject;
    }
    
    @RequestMapping("/doctopdf/{id}")
    public void docTopdf(@PathVariable("id") Integer id, HttpServletResponse response, HttpServletRequest request) throws Exception {
        FileObject fileObject = fileObjectService.findById(id);
        String realPath = request.getSession().getServletContext().getRealPath("/download");
        String fileName = fileObject.getName().replace("-", "").substring(20) + "." + fileObject.getId() + "." + fileObject.getSuffix();
        realPath  =realPath + "/" + fileName;
        System.out.println(realPath);
    }


}
